package com.wpml.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpml.common.constant.RedisKey;
import com.wpml.common.util.RedisUtil;
import com.wpml.product.dao.CategoryDao;
import com.wpml.product.entity.CategoryModel;
import com.wpml.product.service.CategoryBrandRelationService;
import com.wpml.product.service.CategoryService;
import com.wpml.product.vo.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品三级分类(PmsCategory)表服务实现类
 *
 * 缓存穿透
 *
 * @author makejava
 * @since 2020-04-07 11:33:36
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryModel> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedissonClient redisson;

    @Override
    public List<CategoryModel> listWithTree() {
        //1、查出所有分类
        List<CategoryModel> entities = baseMapper.selectList(null);

        return entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildren(menu, entities)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    //递归查找所有菜单的子菜单
    private List<CategoryModel> getChildren(CategoryModel root, List<CategoryModel> all) {

        return all.stream()
                .filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }


    /**
     * 级联更新所有关联的数据
     * 删除分类缓存信息
     *
     * @param category
     */
    /*@Caching(evict = {
            @CacheEvict(value = RedisKey.CATEGORY_CACHE_GROUP, key = "'"+ RedisKey.INDEX_CATEGORY_ONE_KEY +"'"),
            @CacheEvict(value = RedisKey.CATEGORY_CACHE_GROUP, key = "'"+ RedisKey.INDEX_CATEGORY_CHILD_KEY +"'")
    })*/
    // 删除该分组下的所有缓存
    @CacheEvict(value = RedisKey.CATEGORY_CACHE_GROUP, allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryModel category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return ArrayUtil.toArray(parentPath, Long.class);
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryModel byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;

    }

    /**
     * @description: 一级分类
     * @author: wang pei
     * @date: 2020/7/1 11:07
     **/
//    @Cacheable(value = "category", key = "#root.methodName")
    @Cacheable(value = RedisKey.CATEGORY_CACHE_GROUP, key = "'"+ RedisKey.INDEX_CATEGORY_ONE_KEY +"'", sync = true)
    @Override
    public List<CategoryModel> getLevelOneCategoryList() {

        System.out.println("获取一级分类信息。。。");

        List<CategoryModel> categoryModels = baseMapper.selectList(new LambdaQueryWrapper<CategoryModel>()
                .eq(CategoryModel::getParentCid, 0).eq(CategoryModel::getShowStatus, 1));

        if (CollUtil.isEmpty(categoryModels)) {
            categoryModels = new ArrayList<>();
        }

        return categoryModels;
    }

    /**
     * @description: 注解缓存示例   二级分类
     * @author: wang pei
     * @date: 2020/7/1 11:04
     **/
    @Cacheable(value = RedisKey.CATEGORY_CACHE_GROUP, key = "'"+ RedisKey.INDEX_CATEGORY_CHILD_KEY +"'")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        System.out.println("查询数据库。。。");
        // 获取所有分类信息
        List<CategoryModel> categoryList = baseMapper.selectList(new LambdaQueryWrapper<CategoryModel>()
                .eq(CategoryModel::getShowStatus, 1));

        // 获取一级分类
        List<CategoryModel> categoryModels = getCategoryListByParentId(categoryList, 0L);
        // 封装返回值
        return categoryModels.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 获取二级分类
            List<CategoryModel> category2List = getCategoryListByParentId(categoryList, v.getCatId());

            List<Catalog2Vo> c2List = new ArrayList<>();

            if (CollUtil.isNotEmpty(category2List)) {
                c2List = category2List.stream().map(c2 -> {
                    // 获取三级分类
                    List<CategoryModel> category3List = getCategoryListByParentId(categoryList, c2.getCatId());
                    // 封装3级分类
                    List<Catalog2Vo.Catalog3Vo> c3List = null;

                    if (CollUtil.isNotEmpty(category3List)) {
                        c3List = category3List.stream().map(c3 -> new Catalog2Vo.Catalog3Vo(
                                String.valueOf(c2.getCatId()), c3.getCatId().toString(), c3.getName())).collect(Collectors.toList()
                        );
                    }

                    return new Catalog2Vo(v.getCatId().toString(), c3List, c2.getCatId().toString(), c2.getName());
                }).collect(Collectors.toList());

            }

            return c2List;
        }));

    }

    /**
     * @description: 原生redis缓存示例
     * @author: wang pei
     * @date: 2020/7/1 11:06
     **/
    @Deprecated
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {

        // 第一次验证缓存是否存在
        Object val = redisUtil.get(RedisKey.INDEX_CATEGORY_CHILD_KEY);

        if (Objects.nonNull(val)) {
            return JSON.parseObject(val.toString(), new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        }

//        return getCatalogJsonLocalLock();
        return getCatalogJsonRedissonLock();
//        return getCatalogJsonRedisLock();
    }

    /**
     * @description: 分布式锁实现 （redisson 实现） 锁自动续期
     * @author: wang pei
     * @date: 2020/6/23 17:21
     **/
    public Map<String, List<Catalog2Vo>> getCatalogJsonRedissonLock() {

        RLock lock = redisson.getLock(RedisKey.CATEGORY_LOCK);
        lock.lock(); // 阻塞等待

        Map<String, List<Catalog2Vo>> dataFromDb;
        try {
            // 查询数据
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    /**
     * @description: 分布式锁实现 （原生 redis 实现）
     * @author: wang pei
     * @date: 2020/6/23 17:21
     **/
    public Map<String, List<Catalog2Vo>> getCatalogJsonRedisLock() {
        // 3d6dcc5e9fab4decbe9f49cfb65822c0
        String uuid = UUID.fastUUID().toString(true);
        // 通过redis 的 setnx 命令实现加锁操作
        boolean lock = redisUtil.lock(RedisKey.CATEGORY_LOCK, uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                // 查询数据
                dataFromDb = getDataFromDb();
            } finally {
                // 释放锁 （通过 lua 脚本实现其原子操作）
                redisUtil.releaseLock(RedisKey.CATEGORY_LOCK, uuid);
            }
            return dataFromDb;
        } else {
            // 获取锁失败，重试
            return getCatalogJsonRedisLock();
        }
    }

    public static void main(String[] args) {
        System.out.println(UUID.fastUUID().toString(true));

    }

    /**
     * @description: 本地锁实现
     * @author: wang pei
     * @date: 2020/6/23 17:08
     **/
    private Map<String, List<Catalog2Vo>> getCatalogJsonLocalLock() {

        synchronized (this) {

            return getDataFromDb();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {

        // 第二次验证缓存是否存在，控制高并发下多次查询数据库
        Object val = redisUtil.get(RedisKey.INDEX_CATEGORY_CHILD_KEY);

        if (Objects.nonNull(val)) {
            return JSON.parseObject(val.toString(), new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        }

        System.out.println("查询数据库。。。");
        // 获取所有分类信息
        List<CategoryModel> categoryList = baseMapper.selectList(new LambdaQueryWrapper<CategoryModel>()
                .eq(CategoryModel::getShowStatus, 1));

        // 获取一级分类
        List<CategoryModel> categoryModels = getCategoryListByParentId(categoryList, 0L);
        // 封装返回值
        Map<String, List<Catalog2Vo>> catalogMap = categoryModels.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 获取二级分类
            List<CategoryModel> category2List = getCategoryListByParentId(categoryList, v.getCatId());

            List<Catalog2Vo> c2List = new ArrayList<>();

            if (CollUtil.isNotEmpty(category2List)) {
                c2List = category2List.stream().map(c2 -> {
                    // 获取三级分类
                    List<CategoryModel> category3List = getCategoryListByParentId(categoryList, c2.getCatId());
                    // 封装3级分类
                    List<Catalog2Vo.Catalog3Vo> c3List = null;

                    if (CollUtil.isNotEmpty(category3List)) {
                        c3List = category3List.stream().map(c3 -> new Catalog2Vo.Catalog3Vo(
                                String.valueOf(c2.getCatId()), c3.getCatId().toString(), c3.getName())).collect(Collectors.toList()
                        );
                    }

                    return new Catalog2Vo(v.getCatId().toString(), c3List, c2.getCatId().toString(), c2.getName());
                }).collect(Collectors.toList());

            }

            return c2List;
        }));

        redisUtil.set(RedisKey.INDEX_CATEGORY_CHILD_KEY, JSON.toJSONString(catalogMap));

        return catalogMap;
    }

    private List<CategoryModel> getCategoryListByParentId(List<CategoryModel> categoryList, Long parentId) {

        return categoryList.stream().filter(item -> Objects.equals(item.getParentCid(), parentId)).collect(Collectors.toList());
    }
}
